import React, { useImperativeHandle, useState } from 'react'
import { Form, Modal, message, Tree } from 'antd'
import { IModalProps, ModelAction } from '@/types/modal'
import { usePermissionStore } from '@/store/permission'
import { IPermission, IRoleItem } from '@/types/roles'
import { IMenuItem } from '@/types/menu'
import { updatePermission } from '@/api/roles'
import { useRouteLoaderData } from 'react-router-dom'
import { IAuthLoader } from '@/router/AuthLoader'

const setPermission: React.FC<IModalProps<IRoleItem>> = props => {
  const [visiable, setVisiable] = useState(false)
  const [roleInfo, setRoleInfo] = useState<IRoleItem>()
  const [checkedKeys, setCheckedKeys] = useState<string[]>([])
  const [permission, setPermission] = useState<IPermission>()
  // const { menuList } = usePermissionStore()
  const { menuList } = useRouteLoaderData('root') as IAuthLoader

  // 自定义mRef,将open方法暴露给父组件使用
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  // 显示
  const open = (type: ModelAction, data?: IRoleItem) => {
    console.log('open:', type, data)
    setVisiable(true)
    setRoleInfo(data)
    setCheckedKeys(data?.permissionList.checkedKeys || [])
    setPermission({
      _id: data?._id || '',
      permissionList: { ...data?.permissionList }
    })
  }

  const handleCheck = (checkedKeysValue: any, item: any) => {
    setCheckedKeys(checkedKeysValue)
    console.log('handleCheck:', item.checkedNodes)

    const _checkedKeys: string[] = []
    const _parentKeys: string[] = []
    item.checkedNodes.map((node: IMenuItem) => {
      if (node.menuType === 2) {
        _checkedKeys.push(node._id)
      } else {
        _parentKeys.push(node._id)
      }
    })
    setPermission({
      _id: roleInfo?._id || '',
      permissionList: {
        checkedKeys: _checkedKeys,
        halfCheckedKeys: _parentKeys.concat(item.halfCheckedKeys)
      }
    })
  }

  // 提交
  const handleSubmit = async () => {
    if (permission) {
      await updatePermission(permission)
      message.success('设置权限成功')
      onCancel()
      props.update()
    }
  }

  // 关闭
  const onCancel = () => {
    setVisiable(false)
    setPermission(undefined)
  }

  return (
    <Modal
      title='设置权限'
      width={800}
      okText='确定'
      cancelText='取消'
      open={visiable}
      onCancel={onCancel}
      onOk={handleSubmit}
    >
      <Form labelAlign='right' labelCol={{ span: 4 }}>
        <Form.Item label='角色名称'>{roleInfo?.roleName}</Form.Item>
        <Form.Item label='权限'>
          <Tree
            checkable
            defaultExpandAll
            checkedKeys={checkedKeys}
            treeData={menuList}
            onCheck={handleCheck}
            fieldNames={{ title: 'menuName', key: '_id', children: 'children' }}
            titleRender={nodeData => (
              <div>
                <span>{nodeData.menuName}</span>
                <span style={{ marginLeft: 8 }}>({nodeData._id})</span>
              </div>
            )}
          ></Tree>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default setPermission
